//index.js
let app = getApp()
let NORMAL = 0, LOWER = 1, PULLDOWN = 2
let goodsList = {
  saveHidden: true,
  totalPrice: 0.0,
  allSelect: true,
  noSelect: false,
  list: [],
  // localList: [],
  // inputNumberStr: '1',
}

Page({
  data: {
    goodsList:{
      saveHidden: true,
      totalPrice:0.0,
      allSelect: true,
      noSelect: false,
      list:[],
      // localList: [],
      // inputNumberStr: '1'
    },
    delBtnWidth:120,    //删除按钮宽度单位（rpx）,
    offset: 1,
    limit: 10,
    loading: false,
    loadingComplete: false,
    loaded: false,
    noConnect: false,
  },
 
 //获取元素自适应后的实际宽度
  getEleWidth:function(w){
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750/2)/(w/2);  //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res/scale);
      return real;
    } catch (e) {
      return false;
     // Do something when catch error
    }
  },
  initEleWidth:function(){
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth:delBtnWidth
    });
  },
  onLoad: function () {
      this.initEleWidth()
      // this.loginCheck()
      //this.getShopCartList()
      //this.addToCart()
      //this.login()
      this.onShow()
  },
  onShow: function(){
    this.setData({
      offset: 1,
      limit: 10,
      loading: false,
      loadingComplete: false,
      loaded: false,
      noConnect: false,
    })
    this.getShopCartList(NORMAL)
    
  },

  /**
   * 下拉刷新  
   */
  onPullDownRefresh: function () {
    this.data.offset = 1
    this.setData({
      loading: false,
      loadingComplete: false,
      loaded: false,
      noConnect: false
    })
    wx.showNavigationBarLoading()
    this.getShopCartList(PULLDOWN)
  },

  /**
   * view滚动到底部触发的事件
   */
  onReachBottom: function () {
    console.log("toLower" + this.data.loadingComplete)
    console.log(this.data.goodsList.list.length)
    this.setData({
      loading: this.data.loading,
      loadingComplete: this.data.loadingComplete
    })
    if (!this.data.loadingComplete) {
      this.data.offset += 1
      this.getShopCartList(LOWER)
    }
  },

  toIndexPage:function(){
      wx.switchTab({
            url: "/pages/index/index"
      });
  },

  touchS:function(e){
    if(e.touches.length==1){
      this.setData({
        startX:e.touches[0].clientX
      });
    }
  },
  touchM:function(e){
  var index = e.currentTarget.dataset.index;

    if(e.touches.length==1){
      var moveX = e.touches[0].clientX;
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var left = "";
      if(disX == 0 || disX < 0){//如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      }else if(disX > 0 ){//移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-"+disX+"px";
        if(disX>=delBtnWidth){
          left = "left:-"+delBtnWidth+"px";
        }
      }
      var list = this.data.goodsList.list;
      if(index!="" && index !=null){
        list[parseInt(index)].left = left; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
    }
  },

  touchE:function(e){
    var index = e.currentTarget.dataset.index;    
    if(e.changedTouches.length==1){
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth/2 ? "margin-left:-"+delBtnWidth+"px":"margin-left:0px";
      var list = this.data.goodsList.list;
     if(index!=="" && index != null){
        list[parseInt(index)].left = left; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);

      }
    }
  },
  delItem: function(e){
    let id = e.currentTarget.dataset.id
    let index = e.currentTarget.dataset.index
    let list = this.data.goodsList.list
    list.splice(index, 1)
    this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list)
    this.delItemFromServer(id)
  },
  selectTap:function(e){
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
        list[parseInt(index)].active = !list[parseInt(index)].active ; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
    }

    var status = list[parseInt(index)].active? 1: 0
    this.changeStatus(id, status)
  },
   totalPrice:function(){
      var list = this.data.goodsList.list;
      var total = 0;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(curItem.active){
            total+= parseFloat(curItem.price)*curItem.number;
          }
      }
      total = parseFloat(total.toFixed(2));//js浮点计算bug，取两位小数精度
      return total;
   },
   allSelect:function(){
      var list = this.data.goodsList.list;
      var allSelect = false;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(curItem.active){
            allSelect = true;
          }else{
             allSelect = false;
             break;
          }
      }
      return allSelect;
   },
   noSelect:function(){
      var list = this.data.goodsList.list;
      var noSelect = 0;
      for(var i = 0 ; i < list.length ; i++){
          var curItem = list[i];
          if(!curItem.active){
            noSelect++;
          }
      }
      if(noSelect == list.length){
         return true;
      }else{
        return false;
      }
   },
   setGoodsList:function(saveHidden,total,allSelect,noSelect,list){
      this.setData({
        goodsList:{
          saveHidden:saveHidden,
          totalPrice:total.toFixed(2),
          allSelect:allSelect,
          noSelect:noSelect,
          list:list
        }
      })
      goodsList = this.data.goodsList
      var shopCarInfo = {};
      var tempNumber = 0;
      shopCarInfo.shopList = list;
      for(var i = 0;i<list.length;i++){
        tempNumber = tempNumber + list[i].number
      }
      shopCarInfo.shopNum = tempNumber;
      wx.setStorage({
        key:"shopCarInfo",
        data:shopCarInfo
      })
   },
   bindAllSelect:function(){
     console.log('')
      var currentAllSelect = this.data.goodsList.allSelect;
      var list = this.data.goodsList.list;
      if(currentAllSelect){
        for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = false;
        }
      }else{
        for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = true;
        }
      }
     for (var i = 0; i < list.length; i++) {
       var status = list[i].active ? 1 : 0
       this.changeStatus(list[i].id, status)
     }
      this.setGoodsList(this.getSaveHide(),this.totalPrice(),!currentAllSelect,this.noSelect(),list);
   },
   jiaBtnTap:function(e){
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;
    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
      if(list[parseInt(index)].number < 100){
        list[parseInt(index)].number++; 
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
    }
     this.changeGoodsNumber(id, list[parseInt(index)].number)
   },
   jianBtnTap:function(e){
    var index = e.currentTarget.dataset.index;
    var id = e.currentTarget.dataset.id;

    var list = this.data.goodsList.list;
    if(index!=="" && index != null){
      if(list[parseInt(index)].number > 1){
        list[parseInt(index)].number-- ;
        this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
    }
     this.changeGoodsNumber(id, list[parseInt(index)].number)
   },
   editTap:function(){
     var list = this.data.goodsList.list;
     for(var i = 0 ; i < list.length ; i++){
            var curItem = list[i];
            curItem.active = false;
     }
     this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
   },
  saveTap:function(){
    var list = this.data.goodsList.list;
    for(var i = 0 ; i < list.length ; i++){
      var curItem = list[i];
      //curItem.active = true;
    }
    this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
  },

   getSaveHide:function(){
     var saveHidden = this.data.goodsList.saveHidden;
     return saveHidden;
   },

  delSelected:function(){
    let list = this.data.goodsList.list
    let listKeep = this.data.goodsList.list
    let listDel = [];
      listKeep = list.filter(function(curGoods) {
      return !curGoods.active;
    });
    listDel = list.filter(function (curGoods) {
      return curGoods.active;
    });

    this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), listKeep);
    this.delSelectedFromServer(listDel)
  },

  toPayOrder: function(){
    this.navigateToPayOrder()
  },
  navigateToPayOrder: function (order) {
    //wx.hideLoading();
    wx.navigateTo({
      url:"/pages/to-pay-order/index"
    })
  },
  /**
   * 获取购物车列表
   */
  getShopCartList: function (flag) {

    if (flag == LOWER) {
      this.setData({
        loading: true,
      })
    }

    let token = wx.getStorageSync('token')
    let that = this
    console.log('getcartlist')
    wx.request({
      url: app.apiUrl('/cart/index'),
      method: 'GET',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        page: that.data.offset,
        page_size: that.data.limit
      },
      success: function (res) {
        console.log(res.data)
        let listTemp = []
        let loadingComplete = false
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
          that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), [])
          that.setData({
            loaded: true
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } else {
          for (var i = 0; i < res.data.data.length; i++) {
            res.data.data[i].pic = app.globalData.imgUrl + res.data.data[i].product.file.savepath + res.data.data[i].product.file.savename
            res.data.data[i].price = res.data.data[i].product.price.toFixed(2)
            res.data.data[i].number = res.data.data[i].num
            // res.data.data[i].number = 0
            res.data.data[i].left = 'margin-left:0px'
            res.data.data[i].active = res.data.data[i].status == 1 ? true : false
          }

          //that.data.goodsList.list = res.data.data
          listTemp = res.data.data

          if (flag == LOWER) {
            that.data.goodsList.list = that.data.goodsList.list.concat(listTemp)
            
            that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), that.data.goodsList.list)
          }
            
          else 
            that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), listTemp)

          if (!(res.data.data.length == that.data.limit)) {
            loadingComplete = true

          }

          that.setData({
            loadingComplete: loadingComplete
          })

        }
      
      },
      fail: function (res) {
        that.setData({
          noConnect: true
        })
        // wx.showModal({
        //   title: '提示',
        //   content: '网络请求异常',
        //   showCancel: false
        // })
      },
      complete: function (res) {
        that.setData({
          loaded: true
        })
        if (flag == LOWER) {
          that.setData({
            loading: false,
          })
        } else if (flag == PULLDOWN) {
          wx.hideNavigationBarLoading() //完成停止加载
          wx.stopPullDownRefresh() //停止下拉刷新
        }
      }
    })
  },

/**
 * 改变购物车状态
 */
  changeStatus: function (id, status) {

    let token = wx.getStorageSync('token')
    let that = this
    //console.log(token)
    wx.request({
      url: app.apiUrl('/cart/changestatus'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        cart_item_id: id,
        cart_item_status: status
      },
      success: function (res) {
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        }

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

/**
 * 更新购物车商品数量
 */
  changeGoodsNumber: function (id, number) {
    let token = wx.getStorageSync('token')
    let that = this
    wx.request({
      url: app.apiUrl('/cart/changegoodsnumber'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        cart_item_id: id,
        number: number
      },
      success: function (res) {
        console.log(res.data)
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } 

      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
  * 从服务器删除购物车商品
  */
  delItemFromServer: function (id) {
    console.log('deleteID:' + id)
    let token = wx.getStorageSync('token')
    let that = this
    //console.log(token)
    wx.request({
      url: app.apiUrl('/cart/del'),
      method: 'POST',
      header: {
        "Authorization": 'Bearer ' + token
      },
      data: {
        cart_item_id: id,
      },
      success: function (res) {
        if (res.data.code > app.globalData.successCode) {
          wx.showToast({
            title: res.data.error_message ? res.data.error_message : app.globalData.unknownError,
            icon: 'none',
            duration: 2000
          })
        } else if (res.data.code == app.globalData.successCode) {
          app.login(that, 0)
        } 
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
        // wx.hideToast()
        //console.log(res)
      }
    })
  },

  /**
   * 从服务器删除选中的商品
   */
  delSelectedFromServer: function (list) {
    console.log(list)
    for (var i = 0; i < list.length; i++) 
      this.delItemFromServer(list[i].id)
  },

  /**
   * 输入框失去焦点
   */
  bindBlur: function (e) {
    console.log(e.detail.value)
    let num = parseInt(e.detail.value)
    let id = e.currentTarget.dataset.id 
    let index = e.currentTarget.dataset.index
    let list = this.data.goodsList.list
    let that = this


    if (isNaN(num)) {
      wx.showToast({
        title: '请输入整数',
        icon: 'none',
        duration: 2000
      })
      //list[parseInt(index)].number = num
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
    } else if (num == 0){
      wx.showModal({
        title: '提示',
        content: '确定从购物车中删除此商品？',
        success: function (res) {
          if (res.confirm) {
            list.splice(index, 1)
            that.setGoodsList(that.getSaveHide(), that.totalPrice(), that.allSelect(), that.noSelect(), list)
            that.delItemFromServer(id)
          } else if(res.cancel) {
            console.log('取消')
          }
        }
      })
    } else {
      if (num > 100)
        num = 100 
      list[parseInt(index)].number = num
      this.setGoodsList(this.getSaveHide(), this.totalPrice(), this.allSelect(), this.noSelect(), list);
      this.changeGoodsNumber(id, num)
    }
  },

  /**
   * token过期，重新登录
   */
  relogin: function () {
    app.globalData.token = null
    app.login()
    this.onShow()
  },

  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.product_id + "&type=0"
    })
  },

})
